package nl.hanze.designpatterns.io;

import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;

import nl.hanze.designpatterns.domain.Answer;
import nl.hanze.designpatterns.domain.FAQcomponent;
import nl.hanze.designpatterns.domain.Question;

public class FAQBuilder {

	
	/* 
	 * Problems:
	 * hoe maak je de boom aan en te gebruiken door de gui?
	 * hoe weet je welk object je krijgt uit de file zodat je er wat op aan kan roepen?
	 * deze manier blijkt super smerig! 
	 */
	
	private ArrayList<FAQcomponent> faqObjects;  //the unsorted, unlinked deserialized objects from the file
	
	public FAQBuilder(){
		faqObjects = new ArrayList<FAQcomponent>();
		faqObjects = readFile();
		System.out.println(faqObjects);
	}

	private ArrayList<FAQcomponent> readFile(){
		ArrayList<FAQcomponent> temp = new ArrayList<FAQcomponent>();
		
		ObjectInputStream oin = null;
		try {
			oin = new ObjectInputStream(new FileInputStream("tree.ser"));
		} catch (Exception e) {
			
		}
			while(true){
				try{
				FAQcomponent obj = (FAQcomponent) oin.readObject();
				temp.add(obj);
			} catch (EOFException e){
				break;
			} catch (ClassNotFoundException e) {
				break;
			} catch (IOException e) {
				break;
			}}
		
		try {
			oin.close();
		} catch (Exception e) {
			
		}
		return temp;
	}
	
	public ArrayList<FAQcomponent> getComponents(){ //returns all the faq objects
		return faqObjects;
	}

	public ArrayList<Question> getRootQuestions(){
		ArrayList<Question> rootquestions = new ArrayList<Question>();
		for(int i = 0; i<faqObjects.size(); i++) //voeg alleen de eerste questions toe in de rij, want dat zijn de roots
		{
			if(faqObjects.get(i) instanceof Question){
				rootquestions.add((Question)faqObjects.get(i));
			}
			else { break; }
		}
		return rootquestions;
	}
	
	public ArrayList<Answer> getAnswers(Question question){
		
		return question.getAnswerobjects();
	}
	
	public static void main(String[] args){
		ArrayList<FAQcomponent> components =new FAQBuilder().getComponents();
		Question firstquestion = (Question) components.get(0);
		System.out.println(firstquestion.getQuestion());
		for(int i = 0; i<firstquestion.getAnswerobjects().size(); i++)
			System.out.println(firstquestion.getAnswerobjects().get(i).getAnswer());
	}
}
